import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Form, Icon, Input, Button, Checkbox, message } from 'antd';
import styles from './login.css';

const FormItem = Form.Item;
class Login extends React.Component {
  constructor(props) {
    super(props);
    this.enterLoading = this.enterLoading.bind(this);
    this.state = {
      loading: false,
      iconLoading: false,
      username: null,
      password: null,
    };
  }

  enterLoading =() => {
    this.setState({
      loading: true,
    });
  }

  stopLoding=() => {
    this.setState({
      loading: false,
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const userName = this.state.username;
    const password = this.state.password;
    this.props.dispatch({
      type: 'login/login',
      payload: { userName, password },
    });
  }

  handleUser=(e) => {
    const username = e.target.value;
    this.setState({ username });
  }

  handlePass=(e) => {
    const password = e.target.value;
    this.setState({ password });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.data.code === 200) {
      message.success(nextProps.data.msg);
      this.props.dispatch(routerRedux.push('/ready'));
    } else if (nextProps.data.code === 500) {
      this.stopLoding();
      message.error(nextProps.data.msg);
    } else if (nextProps.data.code === 304) {
      this.stopLoding();
      message.error(nextProps.data.msg);
    }
  }
  render() {
    return (
      <div className={styles.back}>
        <Form onSubmit={this.handleSubmit} className={styles.loginform}>
          <FormItem>
            {
              <Input
                prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="Username"
                onChange={this.handleUser}
              />
            }
          </FormItem>
          <FormItem>
            {
              <Input
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="Password"
                onChange={this.handlePass}
              />
            }
          </FormItem>
          <FormItem>
            <Button type="primary" htmlType="submit" className={styles.loginformbutton}loading={this.state.loading}onClick={this.enterLoading}>
              Log in
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const LoginForm = Form.create()(Login);

function mapStateToProps(state) {
  const data = state.login.data;
  return { data };
}
export default connect(mapStateToProps)(LoginForm);
